<template>
    <a-form-model ref="form" :model="form" layout="vertical" class="rx-a-form-vertical">

        <a-form-model-item :label="i18n('form.matchMethod','匹配方式')"  >
            <a-radio-group buttonStyle="solid" v-model="form.type">
                <a-radio-button value="table">{{i18n('form.dbTable','数据库表')}}</a-radio-button>
                <a-radio-button value="dictionary">{{i18n('form.dict','数据字典')}}</a-radio-button>
            </a-radio-group>
        </a-form-model-item>

        <template v-if="form.type=='table'">
            <a-form-model-item  :label="i18n('form.dataSource','数据源')" >
                <rx-input-button ref="dsName" v-model="form.dsName" @click="openDataSource"
                ></rx-input-button>
            </a-form-model-item>

            <a-form-model-item   :label="i18n('form.selectionTable','选择表')" >
                <rx-input-button ref="tableName" v-model="form.tableName" @click="onTableMap"
                ></rx-input-button>
            </a-form-model-item>
            <a-form-model-item   :label="i18n('form.searchField','搜索字段')">
                <a-select v-model="form.match" :options="matchCol" @change="changMatch"
                          allowClear :placeholder="i18n('form.searchField','搜索字段','select')">
                </a-select>
            </a-form-model-item>
            <a-form-model-item   :label="i18n('form.searchParams','搜索条件')">
                <div class="table-operator">
                    <a-button @click="addConf">{{$ti18('rxList.add', '新增')}}</a-button>
                    <a-button @click="removeConf">{{$ti18('rxList.delBtn','删除')}}</a-button>
                </div>
                <rx-grid
                    ref="tableConf"
                    :columns="columnsConf"
                    :dataSource="form.whereFields"
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :showPage="false"
                    :bordered="true"
                    style="height:180px;"
                >
                <span slot="field" slot-scope="{text,record,index}">
                  <a-select v-model="record.field" :options="matchCol" @change="handWhereField($event, record)"
                            allowClear style="width: 70%;">
                  </a-select>
                </span>
                    <span slot="valueSource" slot-scope="{text, record, index}">
                    <a-select :defaultValue="text" v-model="record.valueSource" style="width: 100%">
                      <a-select-option value="fixedVar" :key="index">{{i18n('form.fixValue','固定值')}}</a-select-option>
                      <a-select-option value="script" :key="index">{{i18n('form.script','脚本')}}</a-select-option>
                      <a-select-option value="constantVar" :key="index">{{i18n('form.constVar','常量')}}</a-select-option>
                    </a-select>
               </span>
                    <span slot="valueDef" slot-scope="{text, record, index}">
                    <a-input v-if="record.valueSource=='fixedVar'" :defaultValue="text" v-model="record.valueDef"/>
                    <a-input-group v-if="record.valueSource=='script'" compact>
                      <a-button @click="openScriptQuery(record)">...</a-button>
                    </a-input-group>
                    <a-select v-if="record.valueSource=='constantVar'" :defaultValue="text" :options="constantField"
                              v-model="record.valueDef" style="width: 100%"></a-select>
               </span>

                </rx-grid>

            </a-form-model-item>


            <a-form-model-item  :label="i18n('form.displayField','显示字段')">
                <div class="table-operator">
                    <a-button @click="addParam">{{$ti18('rxList.add', '新增')}}</a-button>
                    <a-button @click="removeParam">{{$ti18('rxList.delBtn','删除')}}</a-button>
                </div>
                <rx-grid
                    ref="table"
                    :columns="columns"
                    :dataSource="form.params"
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :showPage="false"
                    :bordered="true"
                    style="height:180px;"
                >
                <span slot="target" slot-scope="{text,record,index}">
                  <a-select v-model="record.field" :options="matchCol" @change="handleFmt($event)" allowClear
                            style="width: 70%;">
                  </a-select>
                </span>
                </rx-grid>

            </a-form-model-item>

            <a-form-model-item   :label="i18n('form.fieldFormat','显示字段格式化')">
                <a-input v-model="form.template"  />
            </a-form-model-item>
        </template>




        <a-form-model-item v-if="form.type=='dictionary'" :label="i18n('form.matchDic','匹配字典')"  >
            <rx-input-button v-model="dicKeyTitle" @click="selectDic"></rx-input-button>
        </a-form-model-item>

    </a-form-model>
</template>

<script>
import FormDbApi from "@/api/form/bo/formDb"
import SysTreeApi from "@/api/system/core/sysTree";
import { Dialog,  Util, App,JsConstant} from "@lowcode/jpaas-common-lib"
import FormCustomQueryApi from '@/api/form/core/formCustomQuery'
import AppName from "@/assets/js/AppName.js";
export default {
    name: "renderConfig_search",
    props: ["layerid", "destroy"],
    mixins:[App,AppName],
    computed: {
        table() {
            return this.$refs.table;
        },
        tableConf() {
            return this.$refs.tableConf;
        },
    },
    created() {

        //常量
        this.loadConstants();
    },
    data() {
        return {
            labelCol: {span: 6},
            wrapperCol: {span: 18},
            matchCol: [],
            dicTree: [],
            form: {
                //table:表,dictionary:数据字典
                type: "",
                //数据源{text:"",value:""}
                dsName: "",
                //表 {text:"",value:""}
                tableName: "",
                //匹配字段
                match: "",
                //类型
                matchDataType: "",
                //[{"target":"NAME_","idx_":"muxehvm337568","serial":1}]
                params: [],
                //[{"idx_":"ovolpnq398637","conf":"TREE_ID_","valueSource":"fixedVar","valueDef":"1555397422375129089",dataType:""}]"
                whereFields: [],
                //模板
                template: "",
                //字典
                dicKey: "",
                dicName:"",
            },
            dicKeyTitle:"",
            columns: [{
                title: this.i18n('form.targetField','目标字段'),
                dataIndex: 'target',
                allowCellEdit: false,
                width: 100,
                scopedSlots: {customRender: 'target'}
            }],

            columnsConf: [
                {
                    title: this.$comi18('listDef.field', '字段'),
                    dataIndex: 'field',
                    allowCellEdit: false,
                    width: 100,
                    scopedSlots: {customRender: 'field'}
                },
                {
                    title: this.$comi18('formDef.valueSource', '值来源'),
                    dataIndex: 'valueSource',
                    allowCellEdit: false,
                    width: 100,
                    scopedSlots: {customRender: 'valueSource'}
                },
                {
                    title: this.i18n('form.defValue','默认值'),
                    dataIndex: 'valueDef',
                    allowCellEdit: false,
                    width: 100,
                    scopedSlots: {customRender: 'valueDef'}
                }
            ],
            constantField: [{label: this.i18n('form.validConst','可用常量'), value: ''}],
        }
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"formCellRender",key);
        },
        changMatch(val) {
            let field = this.getField(val);
            if (field) {
                this.form.matchDataType = field.dataType;
            }

        },
        setData(data, fields) {
            if (data.type) {
                this.form = data;
            }
            if(data.dicKey){
                if(data.dicName){
                    this.dicKeyTitle = {
                        text:data.dicName,
                        value:data.dicKey
                    }
                    return;
                }
                var self_ = this;
                SysTreeApi.listDicTree(this.curApp.appId).then(res => {
                    var cloneData = [];
                    res.forEach(function (item) {
                        cloneData.push({
                            title: item.name,
                            key: item.treeId,
                            value: item.alias,
                            parentId: item.parentId
                        })
                    })
                    var treeData = Util.listToTree(cloneData, "key", "parentId");
                    self_.dicTree = treeData;

                    for (var i = 0; i < self_.dicTree.length; i++) {
                        var item = self_.dicTree[i];
                        //检索出当前选中的数据字典，保存名称和别名
                        if (item.key == data.dicKey) {
                            self_.form.dicKey = item.value;
                            self_.form.dicName = item.title;
                            self_.dicKeyTitle = '{value:\'' + item.value + '\',text:\'' + item.title + '\'}';
                            break;
                        }
                    }
                })

            }
            if (data.type == "table" && data.tableName) {
                let tableObj = JSON.parse(data.tableName);
                let table = tableObj.value;
                this.loadColumn(table);
            }
        },
        selectDic(vm){
            var conf = {
                curVm: this, data: {isFull:true}, widthHeight: ['800px', '600px'],
            }
            let self_ = this;
            Dialog.openSysDicDialog(conf,function (curVue, row) {
                self_.form.dicKey = row.pkId || row.treeId;
                self_.form.dicName = self_.$i18(row.name,"名称")
                vm.setVal(self_.form.dicKey,self_.form.dicName);
            })
        },
        validate(callback) {
            var self = this;
            callback();
        },
        getData() {
            return this.form;
        },
        openDataSource(vm) {
            Dialog.openDataSourceDialog({
                curVm: this, widthHeight: ['1200px', '600px'],
                data: {appName: this.serviceName}
            }, function (self, data) {
                vm.setVal(data.alias, data.name)
            })
        },
        onTableMap(vm) {
            var datasource;
            if (this.form.dsName != undefined && this.form.dsName.indexOf("{")>-1) {
                datasource = JSON.parse(this.form.dsName).value;
            } else {
                datasource = this.form.dsName;
            }
            Dialog.openTableQueryDialog({
                curVm: this, widthHeight: ['1200px', '600px'], data: {ds: datasource}
            }, function (self, data) {
                vm.setVal(data.tableName, data.tableName);
                self.loadColumn(data.tableName);
            })
        },
        loadColumn(tableName) {
            var self_ = this;
            var datasource = "";
            if(this.form.dsName) {
                datasource = JSON.parse(this.form.dsName).value;
            }
            FormDbApi.getByName("dsName=" + datasource + "&tbName=" + tableName).then(data => {
                var column = [];
                for (var i = 0; i < data.columnList.length; i++) {
                    let col = data.columnList[i];
                    column.push({label: col.comment, value: col.fieldName, dataType: col.columnType});
                }
                self_.matchCol = column;
            })
        },
        loadDicTree() {
            SysTreeApi.listDicTree(this.curApp.appId).then(res => {
                var cloneData = [];
                res.forEach(function (item) {
                    cloneData.push({
                        title: item.name,
                        key: item.treeId,
                        value: item.alias,
                        parentId: item.parentId
                    })
                })
                var treeData = Util.listToTree(cloneData, "key", "parentId");
                this.dicTree = treeData;
            })
        },
        getField(field) {
            let fields = this.matchCol.filter(item => {
                return item.value == field;
            });
            if (fields && fields.length > 0) {
                return fields[0]
            }
            return null;
        },

        addParam() {
            let id = Util.randomId();
            let obj = {"field": "", "idx_": id}
            this.form.params.push(obj);
        },
        removeParam() {
            this.table.removeRows();
            let rows = this.table.getData();
            this.form.params = rows;
        },
        addConf() {
            let _idx = Util.randomId();
            let obj = {idx_: _idx, field: "", valueSource: "", valueDef: "", dataType: ""};
            this.form.whereFields.push(obj);
        },
        removeConf() {
            this.tableConf.removeRows();
            let rows = this.tableConf.getData();
            this.form.whereFields = rows;

        },
        handleFmt(val) {
            var template = this.form.template || "";
            this.form.template = template + '{' + val + '}';
        },
        handWhereField(val, record) {
            let field = this.getField(val);
            record.dataType = field.dataType;
        },
        openScriptQuery(record) {
            let script = record.valueDef;
            Dialog.openScripttextDialog({
                curVm: this, widthHeight: ['800px', '600px'], data: {script: script}
            }, function (self, data) {
                record.valueDef = data;
            })
        },
        loadConstants() {
            FormCustomQueryApi.getConstants().then(data => {
                this.constantField = this.constantField.concat(data.map(item => {
                    return {label: item.val, value: item.key}
                }));
            })
        },
    }
}
</script>

<style scoped>

</style>